package com.ycl.javacore.thread.threadlocal;

/**
 * User: OF1089 杨成龙
 * Date: 2020/3/12
 * Time: 1:44 下午
 * Desc: ThreadLocal 实际使用场景
 */
public class RealityScene {

    public static void main(String[] args) {
        Service1 service1 = new Service1();
        for (int i = 0; i < 10; i++) {
            new Thread(service1::process).start();
        }
    }

    private static UserContextHolder userContextHolder = new UserContextHolder();

    public static class Service1 {
        public void process() {
            User user = new User("ycl");
            userContextHolder.holder.set(user);
            new Service2().process();
        }
    }

    public static class Service2 {
        public void process() {
            User user = userContextHolder.holder.get();
            System.out.println(Thread.currentThread().getName() + "，service2拿到用户名：" + user.name);
            new Service3().process();
        }
    }

    public static class Service3 {
        public void process() {
            User user = userContextHolder.holder.get();
            System.out.println(Thread.currentThread().getName() + "，service3拿到用户名：" + user.name);
        }
    }

    public static class UserContextHolder {
        public ThreadLocal<User> holder = new ThreadLocal<>();
    }

    public static class User {
        String name;

        public User(String name) {
            this.name = name;
        }
    }
}
